package br.com.ufpr.sgp.pages.processo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteTextField;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.list.AbstractItem;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.util.string.Strings;
import org.wicketstuff.annotation.mount.MountPath;

import br.com.sebrae.pr.sgp.entities.Cliente;
import br.com.sebrae.pr.sgp.entities.Processo;
import br.com.sebrae.pr.sgp.services.ClienteServiceRemote;
import br.com.sebrae.pr.sgp.services.ProcessoServiceRemote;
import br.com.sebrae.pr.sgp.util.ConversionUtil;
import br.com.sebrae.pr.sgp.util.CustomStringUtils;
import br.com.sgp.util.handling.ErrorHandlingAjaxButton;
import br.com.sgp.util.handling.ErrorHandlingAjaxLink;
import br.com.ufpr.sgp.enums.StatusProcesso;
import br.com.ufpr.sgp.enums.TipoProjeto;
import br.com.ufpr.util.base.BaseLayoutPage;
import br.com.ufpr.util.base.Protected;

@Protected
@MountPath("ConsultarProcessos")
public class ConsultarProcessoPage extends BaseLayoutPage {
	private static final long serialVersionUID = 2266222543795707073L;

	@EJB(name = "ClienteServiceImpl")
	private ClienteServiceRemote clienteServiceRemote;

	@EJB(name = "ProcessoServiceImpl")
	private ProcessoServiceRemote processoServiceRemote;

	private Processo processoPesquisa = new Processo();
	private Cliente cliente;
	private List<Processo> processos = new ArrayList<Processo>();

	static ModalCadastrarProcesso modalProcesso = null;

	// public ConsultarProcessoPage() {
	// this(new CompoundPropertyModel<Processo>(new Processo()));
	// }

	public ConsultarProcessoPage() {
		super(new Model<String>("Consultar Processos"));
		add(new PesquisarProcessoForm("pesquisarProcessoForm", ConsultarProcessoPage.this));
	}

	private class PesquisarProcessoForm extends StatelessForm<ConsultarProcessoPage> {
		private static final long serialVersionUID = -2832873183098470774L;

		@EJB(name = "ProcessoServiceImpl")
		private ProcessoServiceRemote processoServiceRemote;

		private String codigo;
		private String acCliente;
		private StatusProcesso status;

		public PesquisarProcessoForm(final String id, final ConsultarProcessoPage consultarProcessoPage) {
			super(id);

			final WebMarkupContainer wmc = new WebMarkupContainer("tableWMC")
			// {
			// private static final long serialVersionUID = -3905211260404639381L;
			//
			// @Override
			// public boolean isVisible() {
			// return super.isVisible() && (processos.size() > 0);
			// }
			// }
			;
			wmc.setOutputMarkupId(true);

			modalProcesso = new ModalCadastrarProcesso("modalCriarProcesso", consultarProcessoPage.getPageReference()) {
				private static final long serialVersionUID = -8557247592565698513L;

				@Override
				public void onClose(AjaxRequestTarget target) {
					target.add(wmc);
					atualizarFeedbackPanel(target);
				}
			};
			add(modalProcesso);

			add(new TextField<String>("codigo", new PropertyModel<String>(PesquisarProcessoForm.this, "codigo"))
			        .setLabel(new ResourceModel("Número do Processo")));

			add(new AutoCompleteTextField<String>("acCliente", new PropertyModel<String>(PesquisarProcessoForm.this, "acCliente")) {
				private static final long serialVersionUID = 5030997203375266246L;

				@Override
				protected Iterator<String> getChoices(String input) {
					if (!Strings.isEmpty(input)) {
						List<String> nomes = clienteServiceRemote.autoComplete(input);
						return nomes.iterator();
					}
					return null;
				}
			});

			// add(new TextField<String>("acCliente", new PropertyModel<String>(PesquisarProcessoForm.this, "acCliente"))
			// .setLabel(new ResourceModel("Nome do Cliente")));

			// add(new DropDownChoice<StatusProcesso>("status", new Model<StatusProcesso>(StatusProcesso.ESTUDO),
			// Arrays.asList(StatusProcesso
			// .values())).setMarkupId("status"));

			add(new DropDownChoice<StatusProcesso>("status", new PropertyModel<StatusProcesso>(PesquisarProcessoForm.this, "status"),
			        Arrays.asList(StatusProcesso.values())).setMarkupId("status"));

			add(new ErrorHandlingAjaxLink("btnCriarProcesso") {
				private static final long serialVersionUID = -1500492227358080404L;

				@Override
				protected void onClicked(AjaxRequestTarget target) {
					modalProcesso.setProcessoModel(new CompoundPropertyModel<Processo>(new Processo()));
					modalProcesso.show(target);
				}

			});
			
			final RepeatingView repeating = new RepeatingView("repeating") {
				private static final long serialVersionUID = -3905211260404639381L;

				@Override
				public boolean isVisible() {
					return super.isVisible() && (processos.size() > 0);
				}
			};
			wmc.add(repeating);

			add(new ErrorHandlingAjaxButton("btnRealizarPesquisa") {
				private static final long serialVersionUID = -5755458956575289167L;

				@Override
				protected void onSubmitted(AjaxRequestTarget target) {
					if (CustomStringUtils.isNotBlank(acCliente)) {
						Cliente cliente = new Cliente();
						cliente.setNome(acCliente.toString());
						processoPesquisa.setCliente(cliente);
					}

					processoPesquisa.setCodigo(ConversionUtil.getInt(codigo));

					if (status != null) {
						processoPesquisa.setStatus(status.getCodigo());
					}
					processos = processoServiceRemote.efetuarPesquisa(processoPesquisa);

					repeating.removeAll();
					target.add(wmc);
					if (processos != null && processos.size() > 0) {
						AbstractItem item = new AbstractItem(repeating.newChildId());
						item.add(new Label("codigo", "codigo"));
						item.add(new Label("cliente", "cliente"));
						item.add(new Label("status", "status"));
						item.add(new Label("celular", "celular"));
						item.add(new Label("foneComercial","foneComercial"));
						item.add(new Label("btnVerProcesso","Ver Processo"));
						item.add(AttributeModifier.replace("style", new AbstractReadOnlyModel<String>() {
							private static final long serialVersionUID = 1L;

							@Override
							public String getObject() {
								return "background-color:grey"; // : ".table";
							}
						}));
						repeating.add(item);
					} 

					int index = 0;
					for (final Processo p : processos) {
						AbstractItem item = new AbstractItem(repeating.newChildId());
						item.add(new Label("codigo", p.getCodigo()));
						item.add(new Label("cliente", p.getCliente().getNome()));
						item.add(new Label("status", StatusProcesso.getDescricaoByCodigo(p.getStatus())));
						item.add(new Label("celular", p.getCliente().getTelCelular()));
						item.add(new Label("foneComercial", p.getCliente().getTelComercial()));
						
						item.add(new ErrorHandlingAjaxLink("btnVerProcesso", p) {
                            private static final long serialVersionUID = 1L;

							@Override
							protected void onClicked(AjaxRequestTarget target) {
								System.out.println(p.getDescricao());
								modalProcesso.setProcessoModel(new CompoundPropertyModel<Processo>(new Processo()));
								IModel<Processo> processoModel = modalProcesso.getProcessoModel();
								processoModel.getObject().setId(p.getId());
								processoModel.getObject().setCodigo(p.getCodigo());
								processoModel.getObject().setCliente(p.getCliente());
								processoModel.getObject().setStatus(p.getStatus());
								processoModel.getObject().setDescricao(p.getDescricao());
								
								modalProcesso.show(target);
							}

						});
						
						repeating.add(item);
						final int idx = index;
						item.add(AttributeModifier.replace("style", new AbstractReadOnlyModel<String>() {
							private static final long serialVersionUID = 1L;

							@Override
							public String getObject() {
								return (idx % 2 == 1) ? "background-color:lightgrey" : ".table";
							}
						}));

						index++;
					}

				}

			});

			add(wmc);
		}

	}

	public void closeModalCadastrarSMP(final AjaxRequestTarget target) {
		if (modalProcesso != null) {
			modalProcesso.close(target);
		}
	}
}
